package com.freight.order.serviceimpl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.entity.User;
import com.freight.core.service.SettingService;
import com.freight.order.dao.*;
import com.freight.order.dto.EntrustGoodsDto;
import com.freight.order.entity.*;
import com.freight.order.mapper.OrderMainMapper;
import com.freight.order.mapper.QuotationRecordMapper;
import com.freight.order.service.CompanyQuotationRecordService;
import com.freight.order.vo.QuotationRecordVo;
import com.freight.user.dao.VehicleLicenseDao;
import com.freight.user.entity.DriverUser;
import com.freight.user.entity.VehicleLicense;
import com.freight.user.mapper.CompanyVoMapper;
import com.freight.user.mapper.DriverVoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
@Transactional
public class CompanyQuotationRecordServiceImpl implements CompanyQuotationRecordService {

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private CompanyVoMapper companyVoMapper;
    @Autowired
    private DriverVoMapper driverVoMapper;

    @Autowired
    private OrderMainMapper orderMainMapper;

    @Autowired
    private QuotationDetailsDao quotationDetailsDao;

    @Autowired
    private QuotationRecordMapper quotationRecordMapper;

    @Autowired
    private QuotationRecordDao quotationRecordDao;

    @Autowired
    private OrderGoodsDao orderGoodsDao;

    @Autowired
    private OrderOrderDao orderOrderDao;

    @Autowired
    private VehicleLicenseDao vehicleLicenseDao;




    @Override
    public Long entrustGoods(EntrustGoodsDto entrustGoodsDto) {
        User u = securityUtil.getCurrUser();
        if (!u.getUserType().equals(CommonConstant.USER_TYPE_COMPANY) && !u.getUserType().equals(CommonConstant.USER_TYPE_ADMIN)) {
            throw new FreightException("请先登入或者切换货主账号生成订单");
        }
        QuotationRecord quotationRecord=quotationRecordDao.getOne(entrustGoodsDto.getQuotationRecordId());
        OrderGoods orderGoods=orderGoodsDao.getOne(quotationRecord.getOrderGoodsId());


        List<QuotationDetails> details=quotationRecordMapper.getQuotationDetails(quotationRecord.getId());
        if(details == null || details.size()==0){
            throw new FreightException("操作出错");
        }
        QuotationDetails quotationDetails = details.get(0);
        if(orderGoods.getStatus() != 3){
            throw new FreightException("订单该状态下无法操作");
        }
        //判断订单剩余重量和司机承运重量
        if (orderGoods.getGoodWeight()<quotationDetails.getTransGoodWeight()){
            throw new FreightException("货物不足");
        }
        List<Long> list=orderMainMapper.getHangintheairOrder(quotationRecord.getUserId());
        if (list!=null && list.size()!=0) {
            throw new FreightException("当前司机有未完成订单，不可委托");
        }
        quotationRecord.setDriverState("2");
        OrderOrder orderOrder = new OrderOrder();
        ObjectUtil.copyPropertiesIgnoreNull(orderGoods,orderOrder);
        orderOrder.setDriverTotalPrice(quotationDetails.getFreightTotalPrice());
        orderOrder.setDriverUnitPrice(quotationDetails.getFreightUnitPrice());

        DriverUser driverUser = driverVoMapper.getDriverVoUserId(quotationRecord.getUserId());
        if(driverUser!=null && driverUser.getVehicleId()!=null){
            Long vehicleId = driverUser.getVehicleId();

            VehicleLicense vehicleLicense=vehicleLicenseDao.getOne(vehicleId);


            orderOrder.setVehicleId(vehicleId);
        }

        orderOrder.setCompanyUserId(orderGoods.getCompanyUserId());
        orderOrder.setGoodsId(quotationRecord.getOrderGoodsId());
        orderOrder.setDriverUserId(quotationRecord.getUserId());
        orderOrder.setGoodWeight(quotationDetails.getTransGoodWeight());
        orderOrder.setTransGoodWeight(null);
        orderOrder.setRealGoodWeight(null);
        orderOrder.setOrderSource("1");
        orderGoods.setGoodWeight(orderGoods.getGoodWeight()-quotationDetails.getTransGoodWeight());
        if(orderGoods.getGoodWeight() == 0.0 ){
            orderGoods.setStatus(5);
        }
        orderGoodsDao.save(orderGoods);
        orderOrder.setOrderState(0);
        orderOrder.setOrderStateDesc("待司机接单");
        orderOrder.setId(null);
        orderOrder=orderOrderDao.save(orderOrder);
        quotationRecord.setOrderId(orderOrder.getId());
        quotationRecordDao.save(quotationRecord);
        return orderOrder.getId();

    }

    @Override
    public List<QuotationDetails> quotationModifyList(Long quotationId) {

        User u = securityUtil.getCurrUser();

        Specification specification = new Specification<QuotationDetails>() {
            @Override
            public Predicate toPredicate(Root<QuotationDetails> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Long> quotationRecordId = root.get("quotationRecordId");

                List<Predicate> list = new ArrayList<Predicate>();

                list.add(cb.equal(quotationRecordId, quotationId));

                Predicate[] arr = new Predicate[list.size()];

                return query.where(list.toArray(arr)).getRestriction();
            }
        };
        return quotationDetailsDao.findAll(specification);
    }

    @Override
    public Page<QuotationRecordVo> companyQuotationRecord(Long orderGoodsId,String loadTime, Page<QuotationRecordVo> page) {
        securityUtil.getCurrUser();

        OrderGoods orderGoods=orderGoodsDao.getOne(orderGoodsId);
        Page<QuotationRecordVo> list=null;
        if(orderGoods!=null){

            list= quotationRecordMapper.driverQuotationRecord(orderGoodsId,loadTime,page);
            if(list!=null && list.getRecords().size()>0){
                for(int i=0;i<list.getRecords().size();i++){
                    List<Long> recordList=new ArrayList<>();
                    recordList.add(list.getRecords().get(i).getQuotationRecordId());
                    Long[] recordId = new Long[recordList.size()];
                    recordList.toArray(recordId);
                    List<QuotationDetails> detailsList=quotationRecordMapper.getQuotationDetailsIds(recordId);
                    list.getRecords().get(i).setNumber(String.valueOf(detailsList.size()));
                    SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );

                    List<String> details=new ArrayList<>();
                    for(int j=0;j<detailsList.size();j++){
                        QuotationDetails quotationDetails=detailsList.get(j);
                        String str = sdf.format(quotationDetails.getCreateTime());
                        String d="司机 "+" "+str+" "+quotationDetails.getFreightTotalPrice();
                        details.add(d);

                    }
                    list.getRecords().get(i).setDetails(details);
                }
            }

            return list;
        }else {
            throw new FreightException("操作出错");
        }
    }

}
